#!/usr/bin/python3
from gi.repository import GLib

import dbus
import dbus.mainloop.glib
import requests

my_sender=''
my_user=''
server_address=''
server_port=25
server_passwd=''

import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
import datetime
import time

def msg_forward(text):
    ret = True
    try:
        msg=MIMEText(text,'plain','utf-8')
        msg['From']=formataddr(["随身Wifi",my_sender])
        msg['To']=formataddr([my_user,my_user])
        msg['Subject']="短信转发 日期："+time.strftime("%Y/%m/%d/")+'时间：'+time.strftime("%H:%M:%S")
        server=smtplib.SMTP(server_address,server_port)
        server.login(my_sender,server_passwd)
        server.sendmail(my_sender,[my_user,],msg.as_string())
        server.quit()
    except Exception:
        ret=False
    return ret

def msg_added_handler(path, received):
    if not received:
        return
    #print("Receive at "+path)
    msg = bus.get_object("org.freedesktop.ModemManager1",path)
    props_iface = dbus.Interface(msg, "org.freedesktop.DBus.Properties")
    content = props_iface.GetAll("org.freedesktop.ModemManager1.Sms")
    while not content['Text'].strip():
        content = props_iface.GetAll("org.freedesktop.ModemManager1.Sms")
    text = "Number: "+content['Number']+"\nText:\n"+content['Text']+"\nTime: "+content['Timestamp']
    msg_forward(text)

if __name__ == '__main__':
    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
    bus = dbus.SystemBus()
    try:
        object = bus.get_object("org.freedesktop.ModemManager1","/org/freedesktop/ModemManager1/Modem/0")
        object.connect_to_signal("Added", msg_added_handler, dbus_interface="org.freedesktop.ModemManager1.Modem.Messaging")
    except dbus.DBusException:
        traceback.print_exc()
        print(usage)
        sys.exit(1)
    loop = GLib.MainLoop()
    loop.run()
